package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * TurnoverReportVO
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {


        List<Double> turnoverList = new ArrayList<>();

        //1.获取日期列表数据
        List<LocalDate> dataList = getDataList(begin, end);

        //2.构造turnoverList数据,封装到TurnoverReportVO (每一天的营业统计,查询数据库: 表-orders, 条件: 状态-已完成,下单时间)
        //循环变量上面得到的时间list,查出每一天的营业额数据
        //select sum(amount) from orders where status  = 5 and order_time <= endTime and order_time order_time >= begin_time
        dataList.forEach(data -> {
            LocalDateTime beginTime = LocalDateTime.of(data, LocalTime.MIN); //2024-02-23 00:00
            LocalDateTime endTime = LocalDateTime.of(data, LocalTime.MAX);   //2024-02-23 23:59:59.999999999
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Double turnover = ordersMapper.sumByMap(map);
            //处理营业额为空的情况
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });


        //3.返回TurnoverReportVO对象
        return new TurnoverReportVO().builder()
                .dateList(StringUtils.join(dataList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    private List<LocalDate> getDataList(LocalDate begin, LocalDate end) {
        List<LocalDate> dataList = new ArrayList<>();
        //1.构造dataList数据,封装到TurnoverReportVO  (假设:查近7天  2024-02-23 .... 2024-02-29)
        dataList.add(begin);        //02-23
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);  //02-29
            dataList.add(begin);    //[23,24,25,26,27,28,29]
        }
        return dataList;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.构造dataList数据
        List<LocalDate> dataList = getDataList(begin, end);

        //2.构造用户总量totalUserList
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        //查询表-user, 条件:创建时间 select count(*) from user where create_time <= 当天时间最大值
        dataList.forEach(data -> {
            LocalDateTime beginTime = LocalDateTime.of(data, LocalTime.MIN); //2024-02-23 00:00
            LocalDateTime endTime = LocalDateTime.of(data, LocalTime.MAX);   //2024-02-23 23:59:59.999999999
            Integer totalUser = userMapper.countBy(null, endTime);
            totalUserList.add(totalUser);

            //3.构造新增用户newUserList
            //查询表-user, 条件:创建时间 select count(*) from user where create_time <= 当天时间最大值 and create_time >= 当天时间最小值
            Integer newUser = userMapper.countBy(beginTime, endTime);
            newUserList.add(newUser);
        });

        //4.封装 UserReportVO 对象, 并返回
        return UserReportVO.builder()
                .dateList(StringUtils.join(dataList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.调用日期方法,获取 dateList
        List<LocalDate> dateList = getDataList(begin, end);

        //订单总数 totalOrderCount
        //有效订单总数 validOrderCount

        //2.循环遍历日期列表,
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        for (LocalDate date : dateList) {
            // 获取每日订单总数
            // select count(*) from orders where order_time >= 当天00:00:00 and order_time <= 当天23:59:59.9999
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN); //2024-02-23 00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);   //2024-02-23 23:59:59.999999999

            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer dailyOrderCount = ordersMapper.countByMap(map);

            // 获取每日有效订单总数
            // select count(*) from orders where order_time >= 当天00:00:00 and order_time <= 当天23:59:59.9999 and status = 5
            map.put("status", Orders.COMPLETED);
            Integer dailyValidOrderCount = ordersMapper.countByMap(map);

            //4.每日订单数列表 orderCountList
            orderCountList.add(dailyOrderCount);

            //5.每日有效订单数列表 validOrderCountList
            validOrderCountList.add(dailyValidOrderCount);

            //6.订单总数 totalOrderCount
            totalOrderCount += dailyOrderCount;

            //7.有效订单总数 validOrderCount
            validOrderCount += dailyValidOrderCount;
        }

        // 订单总数 totalOrderCount
        // BinaryOperator是个累加器, 创建一个匿名内部类,需要实现apply方法
        // totalOrderCount = orderCountList.stream().reduce(0, new BinaryOperator<Integer>() {
        //     //方法的作用:用于做累加或者计算
        //     @Override
        //     public Integer apply(Integer a, Integer b) {
        //         return a + b;   //做加法
        //     }
        // });

        // totalOrderCount = orderCountList.stream().reduce(0, (a, b) -> {return a + b;});

        // totalOrderCount = orderCountList.stream().reduce(0, (a, b) -> a + b);

        // totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);

        // totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        // 有效订单总数 validOrderCount
        // validOrderCount = validOrderCountList.stream().reduce(0, Integer::sum);


        //5.计算完成率 = 100%  * validOrderCount / totalOrderCount
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = 1.0 * validOrderCount / totalOrderCount;
        }

        //6.构造vo对象并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //查询数据:表-orders+order_detail    条件: 下单时间   +  已完成状态(5)  ---->得到满足条件的订单
        //根据订单id统计商品销量
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN); //2024-02-23 00:00
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);   //2024-02-29 23:59:59.999999999

        List<GoodsSalesDTO> goodsSalesDTOS = ordersMapper.top10(beginTime, endTime, Orders.COMPLETED);

        //1.构造商品名称列表数据 nameList
        List<String> nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());

        //2.构造销量列表数据 numberList
        List<Integer> numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //3.封装成SalesTop10ReportVO对象并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //1.调用工作台的方法，获取近30天营业额数据（排除今天，往前推30天）
        LocalDate begin = LocalDate.now().minusDays(30); //获取当前日期  2024-03-02 然后往前推30天，得到起始时间2024-02-01
        LocalDate end = LocalDate.now().minusDays(1);    //然后往前推1天，得到结束时间 2024-03-01
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.准备好模板文件 ----》运营数据报表模板.xlsx
        //基于模板文件创建工作簿对象  (根据类加载器获取指定文件的类路径)
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheetAt(0);

            //填充时间数据到表格中
            String time = "时间：" + begin + "至" + end;
            sheet.getRow(1).getCell(1).setCellValue(time);

            //3.将查到的数据填充到模板文件中
            //概览数据填充
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());            //营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());            //新增用户数
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());     //有效订单
            row.getCell(4).setCellValue(businessData.getUnitPrice());           //平均客单价

            //每日明细数据填充
            int i = 7;
            while (!begin.isAfter(end)) {    //2024-02-01 00:00  2024-02-01 23:59:59.9999
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(begin, LocalTime.MAX));
                XSSFRow row1 = sheet.getRow(i++);
                row1.getCell(1).setCellValue(begin.toString());
                row1.getCell(2).setCellValue(businessData1.getTurnover());
                row1.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row1.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row1.getCell(5).setCellValue(businessData1.getUnitPrice());
                row1.getCell(6).setCellValue(businessData1.getNewUsers());
                begin = begin.plusDays(1);
            }

            //4.导出excel文件，将文件下载到客户端浏览器【需要用到响应流】
            workbook.write(response.getOutputStream());
            log.info("导入报表成功！！！");

        } catch (Exception e) {
            log.error("数据导出异常！{}", e.getMessage());
            throw new OrderBusinessException("数据导出异常！");
        }finally {
            //5.关闭资源
            if (workbook != null) {
                try {
                    workbook.close();
                    in.close();
                } catch (IOException e) {
                    log.error("关闭资源失败：{}", e.getMessage());
                }
            }
        }

    }
}
